local delay = 20  -- in seconds
local new_timer = ngx.timer.at
local log = ngx.log
local ERR = ngx.ERR
local check
local fetcher = require('fetcher')
-- local mp = require ('MessagePack')
local cjson = require("cjson")

local upserver = ngx.shared.upserver

local action = function ()
  log(ERR, "action")

  local servers = fetcher.fetch() -- servers { type1 : {ip1, ip2}, type2 : {ip1, ip2} }
  -- local tmp1 = mp.pack(servers)
  local tmp1 = cjson.encode(servers)
  upserver:set('server', tmp1)
end


check = function(premature)
  log(ERR, "check")
  if not premature then

    action()
    -- do the health check or other routine work
    local ok, err = new_timer(delay, check)
    if not ok then
      log(ERR, "failed to create timer: ", err)
      return
    end
  end
end

-- new_timer(10, function () check(false) end)

local ok, err = new_timer(10, check)
if not ok then
  log(ERR, "failed to create timer: ", err)
  return
end
